package com.example.petadopt.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petadopt.R;
import com.example.petadopt.common.Result;
import com.example.petadopt.dao.PetDao;
import com.example.petadopt.entity.Pet;
import com.example.petadopt.ui.activity.PetDetailActivity;
import com.example.petadopt.ui.adapter.PetDiscoverAdapter;

import java.util.ArrayList;
import java.util.List;

public class DiscoverFragment extends Fragment {

    private RecyclerView rvPets;
    private TextView tvPetCount;
    private EditText etSearch;
    private ImageView ivSearch;
    private ImageView ivClear;

    private PetDiscoverAdapter adapter;
    private List<Pet> petList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discover, container, false);
        initView(view);
        initListener();
        loadData();
        return view;
    }

    private void initView(View view) {
        rvPets = view.findViewById(R.id.rv_pets);
        tvPetCount = view.findViewById(R.id.tv_pet_count);
        etSearch = view.findViewById(R.id.et_search);
        ivSearch = view.findViewById(R.id.iv_search);
        ivClear = view.findViewById(R.id.iv_clear);

        // 设置RecyclerView
        rvPets.setLayoutManager(new GridLayoutManager(getContext(), 2));
        adapter = new PetDiscoverAdapter(petList);
        rvPets.setAdapter(adapter);
    }

    private void initListener() {
        // 宠物点击事件
        adapter.setOnItemClickListener(new PetDiscoverAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Pet pet, int position) {
                Intent intent = new Intent(getContext(), PetDetailActivity.class);
                intent.putExtra("pet_id", pet.getId());
                startActivity(intent);
            }
        });

        // 搜索框文本变化监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString().trim();
                if (TextUtils.isEmpty(keyword)) {
                    ivClear.setVisibility(View.GONE);
                    // 恢复全部数据
                    loadData();
                } else {
                    ivClear.setVisibility(View.VISIBLE);
                    // 延迟500搜索数据
                    etSearch.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            searchPets(keyword);
                        }
                    }, 500);
                }
            }
        });

        // 清除按钮点击事件
        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        // 搜索按钮点击事件
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyword = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    searchPets(keyword);
                }
            }
        });
    }

    private void loadData() {
        String keyword = etSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(keyword)) {
            searchPets(keyword);
            return;
        }
        Result<List<Pet>> result = PetDao.getAllPets();

        if (result.isSuccess() && result.getData() != null) {
            petList.clear();
            petList.addAll(result.getData());
            adapter.updateData(petList);
            updatePetCount();
        } else {
            Toast.makeText(getContext(), result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void searchPets(String keyword) {
        Result<List<Pet>> result = PetDao.searchPetsByKeyword(keyword);

        if (result.isSuccess() && result.getData() != null) {
            petList.clear();
            petList.addAll(result.getData());
            adapter.updateData(petList);
            updatePetCount();
        } else {
            Toast.makeText(getContext(), result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void updatePetCount() {
        tvPetCount.setText("共找到 " + petList.size() + " 只宠物");
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
} 